<template>
    <div class="divBox">
      <!-- 组织架构页面 -->
      <el-card v-loading="cardloading">
        <el-row>
          <el-col v-bind="gridl" class="p20">
            <tree :parent-tree="treeData" :pagestatus="pagestatus" :treeid="tree_id" @handlerTree="handlerTree"/>
          </el-col>
          <el-col v-bind="gridr" class="boder-left p20">
            <div class="table-box ml20">
                  <!-- 新增(新) -->
                <wlForm v-if="wlformShow" ref="addDrawernew" :treeData="treeData" :pagestatus="pagestatus" :keyName="keyName" @getList="getList"></wlForm>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
</template>

<script>
  import {
    crudModuleListApi,
  crudModuleInfoApi,
  crudModuleDelApi,
  crudModuleFindApi,
  crudFormMatenalListApi,
  crudFormPrcessTreeListApi,
 } from '@/api/develop'
  import { EventBus } from '@/libs/bus'
  export default {
    name: 'box',
    components: {
      wlForm: ()=> import('./components/wlForm'),
      tree: () => import('../../others/components/tree'),
    },
    props: {
      pagestatus: {
         type: Number,
         defaualt: 1,
      },
      selectData: {
        type: [Object, Array],
        default: ()=>{
           return {}
        },
      },
      id: {
        type: Number, 
        default: 0
      }
      
    },
    watch: {
      selectData(newval, oldval) {
         if(newval !== oldval){
            if(JSON.stringify(this.selectData) !='{}'){
              this.getList();
            }
         }
      }
    },
    data() {
      return {
        treeData: [],
        loading: false,
        tableData: [],
        tree_id: 0,
        num: 0,
        personConfig: {},
        total: 0,
        formData: {
          page: 1,
          limit: 15,
          name: ''
        },
        drawer: false,
        gridl: {
          xl: 7,
          lg: 7,
          md: 7,
          sm: 7,
          xs: 24
        },
        gridr: {
          xl: 17,
          lg: 17,
          md: 17,
          sm: 17,
          xs: 24
        },
        formleibie: {
           page: 1, 
           limit: 50,
           keyword_default:'',
        },
        keyName: '',
        info: {},
        isNumber: 0,
        wlformShow: false,
        cardloading: true,
        total: 0,
        wlqdObject: {
           beizhu:'',
           children:[],
           dahuodingliao: '',
           dahuoquedingriqi:'',
           fuwuliaobianmaid:'',
           id:'',
           is_share: false,
           jishu:'',
           label:'',
           labels:'',
           name:'',
           shiyongbumen:'',
           sunhao:'',
           sunhaodaima:'',
           sunhaoleixing:[],
           tiaoji:'',
           wuliaobianmaid:'',
           yangbandingliao:'',
           yangbanquedingriqi:'',
           yongliang:''
        }
        
      }
    },
   
    created() {
        
    },
    mounted() {
        this.keyName = this.handlerUrlName();
        this.getInfo();
        this.getList();

    },
    methods: {
      
      
      handlerUrlName(){
        const routeString = this.$route.path
        const routeArray = routeString.split('/').filter((item) => item !== '')
        return routeArray[3]
      },
      async openBox(data){
          this.getList();
          this.drawer = true;
      },
      getSearch(val){
          this.formleibie.keyword_default = val;
          this.getList();
      },

      async handlerFindDetails(id, index=1){
          this.wlformShow = true;
          const data = await crudModuleFindApi(this.keyName, id)
          this.$nextTick(() => {
            this.$refs.addDrawernew.openBox(id, data.data)
          })
        
      },
      getInfo() {
        crudModuleInfoApi(this.keyName, 0).then((res) => {
            this.info = res.data
        })
      },
      // 树形数据
      async getList(indexid=0) {
        console.log("aaaaq")
          this.tree_id = indexid;
          this.treeData = []
          this.cardloading = true;
          let resdata = null;
          if(this.keyName=='wuliaoleibieshuxing'){
            this.formleibie.limit = 300;
            resdata = await crudModuleListApi(this.keyName, this.formleibie)
          }else if(this.keyName=='gongxushezhong'){
            resdata = await crudFormPrcessTreeListApi()
            // console.log('ersdata', resdata)
          }else{
            resdata = await crudModuleListApi(this.keyName, this.formleibie)
          }
          let resultdata = resdata.data.list;
          let udata = [],treedata2 = [], treeDatas=[]
          console.log("abd")
          if(this.keyName=='gongxushezhong'){ // 工序设置
            treeDatas = resultdata;
            this.total = resultdata.length || 0;
          }else{
            
            for(let a=0;a<resultdata.length;a++){
              let lbname = this.extractedText(resultdata[a].fuwuliaoleibie)
              resultdata[a].labels = lbname; // 父类别代码
              resultdata[a].label = resultdata[a].leibiedaima; // 类别代码
              let lbzwname = this.extractedText(resultdata[a].zhongwenmiaoshu)
              resultdata[a].name = lbzwname; // 中文描述
              udata.push(resultdata[a])
            }
            treedata2 = this.sortedAsc(udata, 'gongxudaima')
            treeDatas = this.buildTreeWithMap(treedata2)
          }
          this.treeData = treeDatas;
          if(indexid){
            this.handlerFindDetails(indexid)
          }else{
            this.handlerFindDetails(this.treeData[0].id)
          }
          console.log("aaaa")
          this.cardloading = false;
      },
    
      // 升序排序函数
      sortedAsc(items, daima) {
        return [...items].sort((a, b) => 
          a.leibiedaima.localeCompare(b.leibiedaima)
        )
      },
      // 移除非中文字符函数
      removeNonChinese(str) {
          // 匹配所有非中文字符，并替换为空
          return str.replace(/[^\u4e00-\u9fa5\u3400-\u4DBF\u{20000}-\u{2A6DF}\u{2A700}-\u{2B73F}\u{2B740}-\u{2B81F}\u{2B820}-\u{2CEAF}\u{2CEB0}-\u{2EBEF}\u{30000}-\u{3134F}\u{F900}-\u{FAFF}]/gu, '');
      },
      // 截取最后一个横杠后的字符和空格前的内容
      extractedText(str) {
          if(str){
            if(str.includes('-')){
              // 找到最后一个横杠的位置
              const lastDashIndex = str.lastIndexOf('-')
              // 找到空格的位置
              const spaceIndex = str.indexOf(' ', lastDashIndex)
              // 截取最后一个横杠后到空格前的内容
              if (lastDashIndex !== -1 && spaceIndex !== -1) {
                return str.substring(lastDashIndex + 1, spaceIndex)
              }
              // 如果没有空格，就取横杠后的所有内容
              else if (lastDashIndex !== -1) {
                return str.substring(lastDashIndex + 1)
              }
              // 如果没有横杠，返回空字符串
              return ''
            }else{
              return str;
            }
          }else{
            return ''
          }
      },
      // 构建树形结构函数
      buildTreeWithMap(data, idKey = 'label', parentKey = 'labels', childrenKey = 'children') {
        const map = {}
        const tree = []
        // 首先构建一个映射表
        data.forEach(item => {
          map[item[idKey]] = { ...item, [childrenKey]: [] }
        })
        // 构建树形结构
        data.forEach(item => {
          const parent = map[item[parentKey]]
          if (parent) {
            parent[childrenKey].push(map[item[idKey]])
          } else if (item[parentKey] === null || item[parentKey] === '') {
            tree.push(map[item[idKey]])
          }
        })
        return tree
      },
      // 选择树形数据或新增物料类别时，获取物料属性数据index值1添加2编辑3删除
      async handlerTree(item='', index=1, indexs=0){
        if(index==1){ // 新增物料类别
          this.$nextTick(() => {
            this.$refs.addDrawernew.openBox(0, '')
          })
        }else if(index==2){ // 编辑
          // this.wlformShow = false;
          this.handlerFindDetails(item.id, index)
        }else if(index==3){ // 删除
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              crudModuleDelApi(this.keyName, item.id).then((deldata)=>{
                if(deldata.status==200){
                  this.$message({ type: 'success', message: res.message })
                }else{
                  this.$message({ type: 'error', message: res.message })
                }
              }).catch((err)=>{
                this.$message({ type: 'error', message: err.message })
              })
           
            }).catch((action) => {
             
            })
        }else if(index==11){ // 新增子类别时，获取物料属性数据index值11添加子类别的物料属性数据
          this.$nextTick(() => {
            this.$refs.addDrawernew.openBox(0, item, 11)
          })
        } else if(index==6){ // 选择当前行
          this.handlerFindDetails(item.id, index)     
        }else{

        }
      },
      // 分页
      pageChange(page) {
        this.formData.page = page
        this.getTableList()
      },
      handleSizeChange(size) {
        this.formData.limit = size
        this.getTableList()
      },
      // 编辑用户
      onEdit(id) {
        this.userId = id
        this.$refs.editUser.open()
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .divBox {
    height: 100%;
  }
  .mt16 {
    margin-top: 7px;
  }
  .img {
    display: block;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 4px;
  }
  
  .prompt-bag {
    background-color: #edf5ff;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #606266;
  }
  /deep/.el-button--small {
    font-size: 13px;
  }
  
  .el-icon-question {
    cursor: pointer;
    color: #1890ff;
    font-size: 15px;
  }
  /deep/ .el-card__body {
    padding: 0 20px;
  }
  .iconzhuyaobumen {
    color: #ff9900;
  }
  .boder-left {
    min-height: calc(100vh - 77px);
    border-left: 1px solid #eeeeee;
  }
  .p20 {
    padding: 20px 0;
  }
  
  .table-container {
    margin-top: 10px;
  }
  
  .frame-name {
    .iconfont {
      padding-right: 6px;
    }
  }
  .icon-h {
    position: relative;
    & > span {
      color: #1890ff;
    }
    .guan {
      color: #ff9900;
    }
  }
  .icon {
    position: absolute;
    top: 0;
    right: -15px;
    display: inline-block;
    width: 15px;
    height: 15px;
    font-size: 10px;
    font-weight: 500;
    text-align: center;
    line-height: 15px;
    color: #fff;
    border-radius: 50%;
    background-color: #ff9900;
  }
  /deep/.select-bar {
    line-height: 32px;
  }
  </style>
  <style>
  .monitor-yt-popover {
    background: #edf5ff;
    border: 1px solid #97c3ff;
    padding: 13px 15px 6px 15px;
  }
  </style>
  